package com.amin.app.web.service;

import com.amin.app.web.entity.SUsers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class MyUserDetailsService implements UserDetailsService {
    private final UserService userService;
    private final RoleService roleService;


    /**
     * 授权的时候是对角色授权，而认证的时候应该基于资源，而不是角色，因为资源是不变的，而用户的角色是会变的
     */
    //private final PasswordEncoder passwordEncoder;

    public MyUserDetailsService(UserService userService, RoleService roleService) {
        this.userService = userService;
        //this.passwordEncoder = passwordEncoder;
        this.roleService = roleService;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SUsers sysUser = userService.getUserInfoByUserName(username);
        System.out.println(sysUser.getUserName());
        if (null == sysUser) {
            throw new UsernameNotFoundException(username);
        }

        String  role = roleService.getRoleById(sysUser.getRoleId()).getRoleCode();
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
        authorities.add(new SimpleGrantedAuthority("ROLE_" + role));
        return new User(sysUser.getUserName(), sysUser.getPassword(), authorities);
    }

}
